package com.guocheng.quartz;

import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class QuartzService {

    @Autowired
    private Scheduler scheduler;

    /**
     * 启动任务调度器
     *
     * @return
     */
    public boolean start() {
        try {
            scheduler.start();
        } catch (SchedulerException e) {
            return false;
        }
        return true;
    }

    /**
     * 停止调度器
     *
     * @return
     */
    public boolean stop() {
        try {
            scheduler.shutdown();
        } catch (SchedulerException e) {
            return false;
        }
        return true;
    }

    /**
     * 将任务和触发器交给调度器
     *
     * @param jobDetail 任务
     * @param trigger   触发器
     * @return
     */
    public Date scheduleJob(JobDetail jobDetail, Trigger trigger) {
        try {
            return scheduler.scheduleJob(jobDetail, trigger);
        } catch (SchedulerException e) {
            return null;
        }
    }

    /**
     * 添加相关的触发器
     *
     * @param trigger
     * @return
     */
    public Date scheduleJob(Trigger trigger) {
        try {
            return scheduler.scheduleJob(trigger);
        } catch (SchedulerException e) {
            return null;
        }
    }

    /**
     * 停止调度Job任务
     * @param triggerkey
     */
    public  boolean unscheduleJob(TriggerKey triggerkey){
        try {
            return scheduler.unscheduleJob(triggerkey);
        } catch (SchedulerException e) {
            return false;
        }
    }

    /**
     * 删除相关的job任务
     *
     * @param jobkey
     * @return
     * @throws SchedulerException
     */
    public boolean deleteJob(JobKey jobkey) {
        try {
            return scheduler.deleteJob(jobkey);
        } catch (SchedulerException e) {
            return false;
        }
    }

    /**
     * 暂停调度中所有的job任务
     */
    public void stopAll() {
        try {
            scheduler.pauseAll();
        } catch (SchedulerException e) {
            throw new RuntimeException("错误");
        }
    }

    /**
     * 恢复调度中所有的job的任务
     */
    public void startAll() {
        try {
            scheduler.resumeAll();
        } catch (SchedulerException e) {
            throw new RuntimeException("错误");
        }
    }
}
